package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.utils.bean.DateRanger;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.domain.SysLogininforDraft;
import com.ruoyi.system.domain.SysLogininforFetcher;
import com.ruoyi.system.domain.SysLogininforTable;
import com.ruoyi.system.domain.dto.SysLogininforListInput;
import com.ruoyi.system.domain.dto.SysLogininforSaveInput;
import com.ruoyi.system.service.ISysLogininforService;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author ruoyi
 */
@Service
@RequiredArgsConstructor
public class SysLogininforServiceImpl implements ISysLogininforService {


    private final JSqlClient sqlClient;

    /**
     * 新增系统登录日志
     *
     * @param logininfor 访问日志对象
     */
    @Override
    public Integer insertLogininfor(SysLogininforSaveInput logininfor) {
        SysLogininfor sysLogininfor = SysLogininforDraft.$.produce(logininfor.toEntity(), draft -> draft.setAccessTime(LocalDateTime.now()));
        return sqlClient.saveCommand(sysLogininfor)
                .setMode(SaveMode.INSERT_ONLY)
                .execute()
                .getTotalAffectedRowCount();
    }

    /**
     * 查询系统登录日志集合
     *
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininfor> selectLogininforList(SysLogininforListInput logininfor, DateRanger dateRanger) {
        SysLogininforTable table = SysLogininforTable.$;
        return sqlClient.createQuery(table)
                .where(table.userName().ilikeIf(logininfor.getUserName()),
                        table.status().eqIf(logininfor.getStatus()),
                        table.ipaddr().ilikeIf(logininfor.getIpaddr())/*,
                        table.loginTime().betweenIf(DateRanger.isAllNotEmpty(dateRanger),dateRanger.getBeginTime(),dateRanger.getEndTime())*/
                )
                .select(table.fetch(SysLogininforFetcher.$.allScalarFields()))
                .execute();
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return 结果
     */
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        SysLogininforTable table = SysLogininforTable.$;
        return sqlClient.createDelete(table).where(table.infoId().in(Arrays.asList(infoIds))).execute();
//        return logininforMapper.deleteLogininforByIds(infoIds);
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor() {
        SysLogininforTable table = SysLogininforTable.$;
        sqlClient.createDelete(table).execute();
    }
}
